#include <iostream>
#include <random>
#include <cstring>
#include <dds/dds.h>
#include "start_atomic_0813_user_permission_service.h" // IDL生成的C语言头文件
#include "../../../include/log_client/LogClient.h"

// DDS实体句柄
static dds_entity_t participant;
static dds_entity_t topic;
static dds_entity_t publisher;
static dds_entity_t writer;

// 清理DDS资源
static void cleanup()
{
    if (writer != DDS_HANDLE_NIL)
        dds_delete(writer);
    if (publisher != DDS_HANDLE_NIL)
        dds_delete(publisher);
    if (topic != DDS_HANDLE_NIL)
        dds_delete(topic);
    if (participant != DDS_HANDLE_NIL)
        dds_delete(participant);
}

// 生成随机用户权限数据
start_atomic_0813_user_permission_service_UserPermissionInput generate_random_user_permission_data()
{
    // 静态随机数生成器（确保全局只初始化一次）
    static std::mt19937 rng(std::random_device{}());
    std::uniform_int_distribution<int> user_id_dist(1000, 9999);         // 用户ID数字部分范围
    std::uniform_int_distribution<int> token_char_dist(0, 61);           // 用于生成token的字符索引
    std::uniform_int_distribution<int> role_idx_dist(0, 3);              // 角色类型索引
    std::uniform_int_distribution<int> action_idx_dist(0, 4);            // 操作类型索引
    std::uniform_int_distribution<int> resource_id_dist(1, 100);         // 资源ID范围

    // 角色类型选项
    const char* roles[] = {"admin", "operator", "viewer", "guest"};
    // 操作类型选项
    const char* actions[] = {"create", "read", "update", "delete", "execute"};
    // 生成token的字符集（62个字符：a-z, A-Z, 0-9）
    const char token_chars[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    const int token_length = 32;                                         // token固定长度

    // 初始化结构体
    start_atomic_0813_user_permission_service_UserPermissionInput data;
    
    // 生成用户ID（格式：user_XXXX）
    int user_id_num = user_id_dist(rng);
    std::string user_id_str = "user_" + std::to_string(user_id_num);
    data.user_id = strdup(user_id_str.c_str());

    // 生成随机token（32位字母数字组合）
    std::string token_str;
    for (int i = 0; i < token_length; ++i) {
        int idx = token_char_dist(rng);
        token_str += token_chars[idx];
    }
    data.token = strdup(token_str.c_str());

    // 随机选择角色类型
    int role_idx = role_idx_dist(rng);
    data.role = strdup(roles[role_idx]);

    // 随机选择操作类型
    int action_idx = action_idx_dist(rng);
    data.action = strdup(actions[action_idx]);

    // 生成资源路径（格式：/resource/entity_XXX）
    int resource_id = resource_id_dist(rng);
    std::string resource_str = "/resource/entity_" + std::to_string(resource_id);
    data.resource = strdup(resource_str.c_str());

    return data;
}

// 释放用户权限数据中的字符串内存
static void free_user_permission_data(start_atomic_0813_user_permission_service_UserPermissionInput& data)
{
    if (data.user_id)
    {
        free(data.user_id);
        data.user_id = nullptr;
    }
    if (data.token)
    {
        free(data.token);
        data.token = nullptr;
    }
    if (data.role)
    {
        free(data.role);
        data.role = nullptr;
    }
    if (data.action)
    {
        free(data.action);
        data.action = nullptr;
    }
    if (data.resource)
    {
        free(data.resource);
        data.resource = nullptr;
    }
}

int main()
{
    // 初始化日志
    LogClient::getInstance().init("mock_atomic_0813_user_permission_service","mock_atomic_0813_user_permission_service");

    dds_return_t rc;

    // 1. 初始化DDS参与者（DomainParticipant）
    participant = dds_create_participant(DDS_DOMAIN_DEFAULT, NULL, NULL);
    if (participant < 0)
    {
        std::cerr << "错误：创建参与者失败，原因：" << dds_strretcode(-participant) << std::endl;
        LogClient::getInstance().logError("创建参与者失败，原因：" + std::string(dds_strretcode(-participant)));
        cleanup();
        return EXIT_FAILURE;
    }

    // 2. 创建主题（Topic），名称需与订阅者一致
    topic = dds_create_topic(
        participant,
        &start_atomic_0813_user_permission_service_UserPermissionInput_desc, // IDL生成的类型描述
        "start_atomic_0813_user_permission_service",                      // 主题名称（必须与订阅者一致）
        NULL, NULL);
    if (topic < 0)
    {
        std::cerr << "错误：创建主题失败，原因：" << dds_strretcode(-topic) << std::endl;
        LogClient::getInstance().logError("创建主题失败，原因：" + std::string(dds_strretcode(-topic)));
        cleanup();
        return EXIT_FAILURE;
    }

    // 3. 创建发布者（Publisher）
    publisher = dds_create_publisher(participant, NULL, NULL);
    if (publisher < 0)
    {
        std::cerr << "错误：创建发布者失败，原因：" << dds_strretcode(-publisher) << std::endl;
        LogClient::getInstance().logError("创建发布者失败，原因：" + std::string(dds_strretcode(-publisher)));
        cleanup();
        return EXIT_FAILURE;
    }

    dds_qos_t *qos = dds_create_qos();
    dds_qset_reliability(qos, DDS_RELIABILITY_RELIABLE, DDS_SECS(10));
    dds_qset_history(qos, DDS_HISTORY_KEEP_LAST, 10);

    // 4. 创建数据写入器（DataWriter）
    writer = dds_create_writer(publisher, topic, qos, NULL);
    if (writer < 0)
    {
        std::cerr << "错误：创建写入器失败，原因：" << dds_strretcode(-writer) << std::endl;
        LogClient::getInstance().logError("创建写入器失败，原因：" + std::string(dds_strretcode(-writer)));
        cleanup();
        return EXIT_FAILURE;
    }
    dds_delete_qos(qos);

    std::cout << "DDS用户权限服务数据发布者已启动，开始发送数据..." << std::endl;
    LogClient::getInstance().logInfo("DDS用户权限服务数据发布者已启动，开始发送数据...");

    // 5. 循环发送数据（持续发送，每次间隔1秒）
    int i = 0;
    while (1)
    {
        // 生成随机用户权限数据
        start_atomic_0813_user_permission_service_UserPermissionInput data = generate_random_user_permission_data();

        // 发送数据
        rc = dds_write(writer, &data);
        if (rc != DDS_RETCODE_OK)
        {
            std::cerr << "错误：dds_write失败，原因：" << dds_strretcode(-rc) << std::endl;
            LogClient::getInstance().logError("dds_write失败，原因：" + std::string(dds_strretcode(-rc)));
            free_user_permission_data(data);
            cleanup();
            return EXIT_FAILURE;
        }

        // 打印发送的信息
        std::string info = "已发送用户权限数据（第" + std::to_string(i + 1) + "次）：\n";
        info += "  用户ID：" + std::string(data.user_id) + "\n";
        info += "  令牌：" + std::string(data.token) + "\n";
        info += "  角色：" + std::string(data.role) + "\n";
        info += "  操作：" + std::string(data.action) + "\n";
        info += "  资源：" + std::string(data.resource);

        std::cout << "==============================" << std::endl;
        std::cout << info << std::endl;
        std::cout << "==============================" << std::endl;
        LogClient::getInstance().logInfo(info);

        // 释放当前数据的字符串内存
        free_user_permission_data(data);

        // 间隔1秒发送
        i++;
        dds_sleepfor(DDS_SECS(1));
    }

    // 清理资源
    cleanup();
    return EXIT_SUCCESS;
}